import {
  DomainCertificateEndpointsClient,
  DomainDto,
} from "@src/services/client";
import { useClient } from "@src/utils/useHelper";
import { createSignal } from "solid-js";
import Swal from "sweetalert2";
import { withSolidContent } from "sweetalert2-solid-content";
import { BsButton, Table } from "solid-fire-controls";

const client = useClient(DomainCertificateEndpointsClient);
const swal = withSolidContent(Swal);

const DomainList = () => {
  const [datas, setDatas] = createSignal<DomainDto[]>([]);
  const load = () => {
    client
      .listDomains()
      .then(setDatas)
      .catch((error) =>
        swal.fire({
          icon: "error",
          text: "加载失败",
        })
      );
  };

  const downloadPfx = (data: DomainDto) => {
    if (data.certificateId) {
      //   client.downloadCertificate(data.certificateId, data.domain);

      window.open(
        `/api/download-pfx?id=${data.certificateId}&downloadName=${data.domain}`
      );
    } else {
      swal.fire({
        icon: "warning",
        title: "无法下载pfx证书",
        text: "没有找到证书",
      });
    }
  };

  const downloadKeyAndCrt = (data: DomainDto) => {
    if (data.certificateId) {
      window.open(
        `/api/download-key-and-crt?id=${data.certificateId}&downloadName=${data.domain}`
      );
    } else {
      swal.fire({
        icon: "warning",
        title: "无法下载key和crt证书",
        text: "没有找到证书",
      });
    }
  };

  return (
    <div class="container">
      <div class="row">
        <div class="col-12">
          <BsButton onclick={load}>查询</BsButton>
        </div>
      </div>
      <div class="row">
        <div class="col-12">
          <Table
            datas={datas()}
            columns={[
              {
                type: "index",
              },
              {
                name: "domain",
                label: "Domain",
              },
              {
                label: "Operations",
                children(data, column, index) {
                  return (
                    <div class="d-flex gap-1">
                      <BsButton
                        size="sm"
                        variant={"light"}
                        onClick={() => downloadPfx(data)}
                      >
                        下载 .pfx
                      </BsButton>
                    </div>
                  );
                },
              },
            ]}
          ></Table>
        </div>
      </div>
    </div>
  );
};

export default DomainList;
